package com.zjuh.goodboy.index.lucene;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.search.Sort;

import com.zjuh.goodboy.index.search.SearchQuery;
import com.zjuh.goodboy.index.search.SortField;
import com.zjuh.goodboy.index.search.SortType;

public class SortUtil {
	
	public static Sort getLuceneSort(SearchQuery searchQuery) {
		if (searchQuery == null) {
			return null;
		}
		List<SortField> sortFields = searchQuery.getSortFields();
		if (sortFields == null || sortFields.isEmpty()) {
			return null;
		}
		List<org.apache.lucene.search.SortField> luceneSortFields = new ArrayList<org.apache.lucene.search.SortField>();
		if (sortFields != null && !sortFields.isEmpty()) {
			for (SortField sortField : sortFields) {
				boolean reverse = (sortField.getSortType() == SortType.DESC);
				org.apache.lucene.search.SortField luceneSortField = 
					new org.apache.lucene.search.SortField(sortField.getName(), org.apache.lucene.search.SortField.STRING, reverse);
				luceneSortFields.add(luceneSortField);
			}
		}
		org.apache.lucene.search.SortField[] luceneSortFieldsArray = luceneSortFields.toArray(new org.apache.lucene.search.SortField[0]);
		return new Sort(luceneSortFieldsArray);
	}

}
